/**
 * 校验是否为控
 * @param target
 * @returns {boolean}
 */
import moment from "moment";
import { fun } from "@/common/index";

export const isEmpty = (target: any) => {
  if (
    target == null ||
    target === "null" ||
    target === "" ||
    target === "undefined" ||
    target === undefined
  ) {
    return true;
  }
  return false;
};
/**
 * 检测是否为空对象
 * @param obj
 * @returns {boolean}
 */
export const isEmptyObj = (obj: any) => JSON.stringify(obj) === "{}";

export const backFunc = () => history.go(-1);

function checkValue(val: any, vals: any) {
  let _val = val;
  if (Number.isNaN(val)) {
    _val = "NaN";
  }
  return vals.indexOf(_val) !== -1;
}

/**
 * 清理对象中多余的属性
 * @param obj
 * @param strice
 * @param tip
 * @param clearValues
 * @returns {*}
 */
export const filterEmptyParams = (opt: {
  obj: {};
  strice?: boolean;
  tip?: string;
  clearValues?: [any];
}) => {
  const {
    obj,
    strice = false,
    tip = false,
    clearValues = [null, undefined, "", "null", "undefined"]
  } = opt;
  const params = Object.assign({}, obj);
  for (const prop in params) {
    if (checkValue(params[prop], clearValues)) {
      if (strice) {
        tip && fun.error({ msg: "参数" + prop + "不能为空" });
        return false;
      }
      // console.log("参数" + prop + "为空被删除");
      delete params[prop];
    }
  }
  return params;
};

/**
 * 查看对象1中的所有属性在obj2中都有
 * @param obj1
 * @param obj2
 */
export const compareObj = (obj1: {}, obj2: {}) => {
  for (const i in obj1) {
    if (!Object.prototype.hasOwnProperty.call(obj1, i)) continue;
    if (!Object.prototype.hasOwnProperty.call(obj2, i) || obj1[i] !== obj2[i]) {
      return false;
    }
  }
  return true;
};

/**
 * 从指定的数组(对象组成的数组)，根据键值和值找到下标
 * @param arr
 * @param key
 * @param val
 * @param full 是否返回值和下标，默认只返回下标
 */
export const findArrayIdx = (arr: [{}], keyValArr: {}, full = false) => {
  for (const i in arr) {
    if (typeof arr[i] !== "object") continue;

    // 用来比较对象
    if (compareObj(keyValArr, arr[i])) {
      if (!full) return i;
      return {
        val: arr[i],
        idx: i
      };
    }
  }
  return false;
};

/**
 * 格式化时间
 * @param str
 * @param fromatStr
 * @param timeStamp
 */
export const formatTime = (str, fromatStr = "YYYY.MM.dd", timeStamp = 0) => {
  if (timeStamp) {
    return moment(new Date(parseInt(str) * 1000)).format(fromatStr);
  }
  return moment(str).format(fromatStr);
};

/**
 * 定时器
 * @param timeNum
 */
export const sleep = (timeNum = 2000,call:any=false) => {
  return new Promise(resolve => {
    setTimeout(() => {
      call && call()
      resolve(true);
    }, timeNum);
  });
};
